package com.ahhwxx.yunmaisdk

import android.app.Activity
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.ahhwxx.lib.ACamera
import com.ahhwxx.lib.CameraActivity
import com.ahhwxx.lib.IdentifyInfo
import com.ahhwxx.lib.utils.QuickRecognition

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<View>(R.id.button).setOnClickListener { view: View? ->
            startActivityForResult(
                Intent(this, CameraActivity::class.java),
                110
            )
        }
        findViewById<View>(R.id.button2).setOnClickListener { view: View? ->
            startActivityForResult(
                Intent(this, ACamera::class.java),
                110
            )
        }
        findViewById<View>(R.id.button3).setOnClickListener { view: View? ->
//            //需要文件读取权限
//            val path =
//                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/palte.jpg"
//            if (!File(path).exists()) {
//                Toast.makeText(this, "图片不存在", Toast.LENGTH_SHORT).show()
//            } else {
//                val identifyInfo = QuickRecognition.getInstance(this).quickPhoto(path)
//                identifyInfo?.let {
//                    findViewById<TextView>(R.id.textview).text = it.toJson()
//                }
//            }
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent, 200)

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 200) {
            val identifyInfo = data?.getSerializableExtra("IdentifyInfo") as IdentifyInfo
            findViewById<TextView>(R.id.textview).text = identifyInfo.toJson()
        }
        if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
            val uri = data?.data as Uri
            val path = getPhotoFilePathFromUri(uri)
            val identifyInfo = QuickRecognition.getInstance(this).quickPhoto(path)
            identifyInfo?.let {
                findViewById<TextView>(R.id.textview).text = it.toJson()
            }
        }
    }

    private fun getPhotoFilePathFromUri(uri: Uri): String {
        val cursor: Cursor? = contentResolver
            .query(uri, null, null, null, null)
        cursor!!.moveToFirst()
        val index: Int = cursor.getColumnIndex(MediaStore.Images.Media.DATA)
        return cursor.getString(index)
    }
}